'use strict';

const packs = require('./pack');

module.exports = class Channel {
  constructor(app) {
    this.app = app;

    this.cache = new Map();
    this.reqs = new Map();
    this.app.messenger.on('iot_action', data => {
      this.onResponse(data);
    });
  }

  onResponse({ id, data, online }) {
    const reqId = `${data.id}@${id}`;
    const req = this.reqs.get(reqId);

    console.log('result', data);
    if (req) {
      req.callback(online ? null : 'offline', data);
    }
  }

  send(terminalId, pack) {
    const id = `${pack.id}@${terminalId}`;
    if (this.cache.has(id)) {
      return this.cache.get(id);
    }
    const reqPromise = new Promise((resolve, reject) => {
      this.app.messenger.sendToAgent('iot_action', {
        id: terminalId,
        data: pack,
      });
      this.reqs.set(id, { callback: (err, data) => {
        this.cache.delete(id);
        if (err) {
          reject(err);
        } else {
          resolve(data);
        }
      } });

      setTimeout(() => {
        this.cache.delete(id);
        reject(new Error('timeout'));
      }, 5000);
    });

    this.cache.set(id, reqPromise);
    return reqPromise;
  }

  get packs() {
    return packs;
  }
};
